package edu.gxmzu.task.config.security;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import edu.gxmzu.task.entity.Accounts;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyUserDetails implements UserDetails {
    private Accounts account;
    private List<String> permissions;  // 权限信息列表
    @JSONField(serialize = false)  // 忽略序列化，redis不支持
    private List<SimpleGrantedAuthority> authorities;

    public MyUserDetails(Accounts account, List<String> permissions) {
        this.account = account;
        this.permissions = permissions;
    }

    // 权限信息
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) return authorities;
        authorities = permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return account.getPassword();
    }

    @Override
    public String getUsername() {
        return account.getUsername();
    }
    // 过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    // 锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    // 凭证过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    // 是否可用
    @Override
    public boolean isEnabled() {
        return true;
    }
}
